package summary;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/13 15:13
 * https://leetcode-cn.com/problems/count-complete-tree-nodes/
 */
public class Title110 {

    static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isBalanced(TreeNode root) {
        return getHigh(root) != -1;
    }

    /**
     * 求树的高度
     * @param root
     * @return
     */
    private int getHigh(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = getHigh(root.left);
        if (left == -1) {
            return -1;
        }
        int right = getHigh(root.right);
        if (right == -1) {
            return -1;
        }
        return Math.abs(left - right) <= 1 ? 1 + Math.max(left, right) : -1;
    }



    public static boolean isBalanced2(TreeNode root) {
        if (root == null) {
            return true;
        }
        return getHeight1(root) != -1;
    }

    /**
     * 获得树的高度
     * @param root
     * @return
     */
    private static int getHeight1(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int left = getHeight1(root.left);
        if (left == -1) {
            return -1;
        }
        int right = getHeight1(root.right);
        if (right == -1) {
            return -1;
        }
        return Math.abs(left - right) <= 1 ? Math.max(left, right) + 1 : -1;
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        TreeNode root1 = new TreeNode(20);
        root1.left = new TreeNode(15);
        root1.right = new TreeNode(7);
        root.right = root1;
        isBalanced2(root);
    }
}
